package m.jclecai.com.adapter.holder;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.LayoutRes;
import android.support.v4.content.ContextCompat;
import android.text.Html;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import m.jclecai.com.R;
import m.jclecai.com.bean.ZqItem;
import m.jclecai.com.dialog.JczqHHDialog;
import m.jclecai.com.listener.MyNotifyTextViewSetChanged;
import m.jclecai.com.listener.OnSclestListener;
import m.jclecai.com.utils.ScreenUtil;
import m.jclecai.com.utils.Utils;
import m.jclecai.com.utils.http.FastOk;

/**
 * Created by ZD on 2017/5/6.
 */

public class BetJczqHolder extends ViewHolder implements View.OnClickListener {
    @BindView(R.id.betting_item_delete)
    ImageView bettingItemDelete;
    @BindView(R.id.home_team_name)
    TextView homeTeamName;
    @BindView(R.id.jclq_fen_name)
    TextView jclqFenName;
    @BindView(R.id.away_team_name)
    TextView awayTeamName;
    @BindView(R.id.ll)
    LinearLayout ll;
    @BindView(R.id.tv_lottery)
    CheckBox tvLottery;
    @BindView(R.id.llspf)
    LinearLayout llspf;
    @BindView(R.id.iv_split)
    ImageView ivSplit;
    @BindView(R.id.betting_item_parent)
    LinearLayout bettingItemParent;
    @BindView(R.id.cb_dan)
    public CheckBox cb_dan;


    //下面的是混投的部分；
    @BindView(R.id.cb_more)
    CheckBox mCbMore;

    @BindView(R.id.ll_hunhe_bet)
    LinearLayout mLlHunheBet;

    @BindView(R.id.ll_spf_odds)
    LinearLayout mLlSpf;


    @BindView(R.id.ll_rspf_odds)
    LinearLayout mLlRqspf;


    @BindView(R.id.tv_spf_txt)
    TextView mTvSpfTxt;

    @BindView(R.id.tv_rqspf_txt)
    TextView mTvRqspfTxt;

    //这里我们要做的一个操作就是总进球
    @BindView(R.id.ll_all)
    LinearLayout mLlZjq;

    @BindView(R.id.ll_zjq_item_one)
    LinearLayout mLlZjqItemOne;

    @BindView(R.id.ll_zjq_item_two)
    LinearLayout mLlZjqItemTwo;

    //===单关的逻辑=====

    @BindView(R.id.cb_dan_guan_more)
    CheckBox mCbDanGuanMore;

    @BindView(R.id.ll_dan_guan)
    LinearLayout mLlDanGuanBet;

    @BindView(R.id.tv_dan_guan_spf_no_sale)
    TextView mTvDanGuanSpfNoSale;

    @BindView(R.id.ll_dan_guan_spf_odds)
    LinearLayout mLlDanGuanSpf;

    @BindView(R.id.tv_dan_guan_rspf_no_sale)
    TextView mTvDanGuanRspfNoSale;

    @BindView(R.id.ll_dan_guan_rspf_odds)
    LinearLayout mLlDanGuanRqspf;


    @BindView(R.id.tv_dan_guan_spf_txt)
    TextView mTvDanGuanSpfTxt;

    @BindView(R.id.tv_dan_guan_rqspf_txt)
    TextView mTvDanGuanRqspfTxt;


    String[] spf;

    ZqItem mItem;
    int mPosition = 0;
    //记录点击的数据
    Map<String, Map<String, String>> cMap;
    MyNotifyTextViewSetChanged changed;
    int mType = 0;
    int pager = 0;
    private SpfPresenter mSpfPresenter;
    private DefaultPresenter mDefaultPresenter;
    private HunTouPresenter mHunTouPresenter;
    private ZjqPresenter mZjqPresenter;
    private DgPresenter mDgPresenter;

    public BetJczqHolder(Context context, @LayoutRes int resource) {
        super(context, resource);
    }

    private void init() {
        init(this.mItem, pager, mPosition);
    }

    public void init(ZqItem item, int pager, int position) {
        this.pager = pager;
        this.mPosition = position;
        this.mItem = item;
        this.mType = pager;
        spf = getContext().getResources().getStringArray(
                R.array.jczq_spf);
        String[] codes = item.getCodes();
        //左边队名-公共属性
        homeTeamName.setText(codes[3]);
        //右边队名-公共属性
        awayTeamName.setText(codes[4]);

        tvLottery.setVisibility(GONE);
        llspf.setVisibility(GONE);
        mLlHunheBet.setVisibility(GONE);
        mLlZjq.setVisibility(GONE);
        mLlDanGuanBet.setVisibility(GONE);

        cb_dan.setChecked(item.isDan_select());


        mDefaultPresenter = new DefaultPresenter();
        mSpfPresenter = new SpfPresenter();
        mHunTouPresenter = new HunTouPresenter();
        mZjqPresenter = new ZjqPresenter();
        mDgPresenter = new DgPresenter();

        if (pager == 0 || pager == 1) {
            mSpfPresenter.init(item);
        } else if (pager == 2) {
            mHunTouPresenter.init(item);
        } else if (pager == 5) {
            //这里要执行的一个操作就是总进球
            mZjqPresenter.init(item);
        } else if (pager == 6) {
            //这里要执行的一个操作就是单关；
            mDgPresenter.init(item);
        } else {
            mDefaultPresenter.init(item);
        }
    }

    /**
     * 解析tag参数
     *
     * @param tag
     * @return
     */
    boolean isCheckThisView(String tag, String index) {
        if (this.mItem.getMap() == null) return false;
        if (this.mItem.getMap().get(index) != null) {
            return this.mItem.getMap().get(index).get(tag) != null;
        }
        return false;
    }

    //显示纯文本
    String showTextUi() {
        //到时候这个排序可以提到外面去 减少计算时间
        Map<String, Map<String, String>> map = mItem.getMap();
        //将key 排序然后显示
        StringBuilder sb = new StringBuilder();
        for (Map<String, String> strMap : map.values()) {
            //勾选的数据 "0_spf_0_2.25_胜" -> "0_spf_0_2.25_胜"
            // 0-服务器数据下标，spf 类型 0-点击的下标用来排序 2.25倍数 胜显示的值
            String[] strs = strMap.keySet().toArray(new String[]{});
            int[] arrayKey = new int[strs.length];
            Map<Integer, String> nMap = new HashMap<>();
            //排序
            for (int j = 0; j < strs.length; j++) {
                String[] split = strs[j].split("_");
                arrayKey[j] = Integer.parseInt(split[2]);
                nMap.put(arrayKey[j], strs[j]);
            }
            Arrays.sort(arrayKey);
            //输出
            for (int j = 0; j < arrayKey.length; j++) {
                String keys = nMap.get(arrayKey[j]);
                String[] split = keys.split("_");
                if (("rqspf").equals(split[1]))
                    sb.append("让");
                sb.append(split[4]);
                if ("jqs".equals(split[1]))
                    sb.append("球");
                sb.append(" ");
            }
        }
        return sb.toString();
    }

    //混投点击更多玩法
    @OnClick(R.id.tv_lottery)
    void more(View v) {
        execCheckParam((CheckBox) v, "点击选择比分");
    }

    /**
     * 处理选中的数据与ui交互
     *
     * @param cb
     * @param buttonText
     */
    void execCheckParam(final CheckBox cb, final String buttonText) {
        // resetCheckBoxStatus(cb, buttonText);
        cb.setChecked(true);
        JczqHHDialog.JCZQSHOWTYPE type;
        if (pager == 3) {
            type = JczqHHDialog.JCZQSHOWTYPE.SHOWBQC;
        } else if (pager == 4) {
            type = JczqHHDialog.JCZQSHOWTYPE.SHOWBF;
        } else if (pager == 5) {
            type = JczqHHDialog.JCZQSHOWTYPE.SHOWZJQ;
        } else if (pager == 6) {
            type = JczqHHDialog.JCZQSHOWTYPE.SHOWDG;
        } else {
            type = JczqHHDialog.JCZQSHOWTYPE.SHOWALL;
        }
        JczqHHDialog dialog = new JczqHHDialog(getContext(), this.mItem.getCodes(), this.mItem.getMap(), type);
        dialog.setListener(new OnSclestListener() {
            @Override
            public void sure(Map<String, Map<String, String>> map) {
                if (mItem.getMap() != null)
                    mItem.getMap().clear();
                mItem.setMap(map);
                String desc = showTextUi();
                cb.setText(desc);
                cb.setChecked(!buttonText.equals(desc));
                init();
                statistics();
            }
        });
        dialog.show();
    }

    //分割线
    public void isShowSplit(boolean show) {
        ivSplit.setVisibility(show ? VISIBLE : GONE);
    }

    @Override
    public void onClick(View v) {
        chekedButtonDoOnClick(v);
    }

    private void chekedButtonDoOnClick(View view) {
        if (mItem.getMap() == null) {
            cMap = new HashMap<>();
            mItem.setMap(cMap);
        } else {
            cMap = mItem.getMap();
        }
        String tag = view.getTag().toString();
        String key = tag.substring(0, 1);
        String value = tag;
        if (cMap.get(key) != null) {
            //有则删除 无则添加 - 等同于没选中则选中 选中了则取消
            if (cMap.get(key).get(value) != null) {
                cMap.get(key).remove(value);
            } else {
                cMap.get(key).put(value, value);
            }
        } else {
            Map<String, String> map = new HashMap<>();
            map.put(value, value);
            cMap.put(key, map);
        }
        if (cMap.get(key) != null && cMap.get(key).values().size() <= 0)
            cMap.remove(key);
        statistics();
    }

    @OnClick(R.id.betting_item_delete)
    void delete() {
        if (Utils.ZQ_ITEM_LIST.contains(mItem)) {
            Utils.ZQ_ITEM_LIST.remove(mItem);
            if (changed != null)
                changed.refreshData();
        }
    }

    //胆码
    @OnClick(R.id.cb_dan)
    void checkDan() {
        mItem.setDan_select(cb_dan.isChecked());
        if (getCheckDan() > Utils.ZQ_ITEM_LIST.size() - 1) {
            cb_dan.setChecked(false);
            mItem.setDan_select(cb_dan.isChecked());
            Toast.makeText(getContext(), "胆码场次超过限制", Toast.LENGTH_SHORT).show();
            return;
        }
        if (changed != null)
            changed.onClickSetChangedText();
    }

    public int getCheckDan() {
        int checkCount = 0;
        for (int i = 0; i < Utils.ZQ_ITEM_LIST.size(); i++) {
            if (Utils.ZQ_ITEM_LIST.get(i).isDan_select())
                checkCount++;
        }
        return checkCount;
    }

    //统计勾选的数据
    private void statistics() {
        if (mItem.getMapLength() > 0) {
            if (!Utils.ZQ_ITEM_LIST.contains(mItem)) {
                if (mPosition < Utils.ZQ_ITEM_LIST.size())
                    Utils.ZQ_ITEM_LIST.add(mPosition, mItem);
                else
                    Utils.ZQ_ITEM_LIST.add(mItem);
            }
        } else {
            if (Utils.ZQ_ITEM_LIST.contains(mItem)) {
                Utils.ZQ_ITEM_LIST.remove(mItem);
                if (changed != null)
                    changed.refreshData();
            }
        }
        if (changed != null)
            changed.onClickSetChangedText();
    }

    public void setChangeListener(MyNotifyTextViewSetChanged change) {
        this.changed = change;
    }

    /**
     * 这个是默认的处理方式；
     */
    public class DefaultPresenter {

        public void init(ZqItem item) {
            tvLottery.setVisibility(VISIBLE);
            resetCheckBoxStatus(tvLottery, "点击选择比分");
        }

        //重置投注按钮状态(CheckBox)
        void resetCheckBoxStatus(final CheckBox cb, final String buttonText) {
            //设置默认选中
            String desc = mItem.getMap() != null && mItem.getMapLength() > 0 ? showTextUi() : buttonText;
            cb.setText(desc);
            cb.setChecked(!buttonText.equals(desc));
        }
    }

    /**
     * 胜平负，让胜平负的一个业务逻辑类
     */
    public class SpfPresenter {
        public void init(ZqItem item) {
            llspf.setVisibility(VISIBLE);
            List<String[]> list = FastOk.getList(item.getCodes()[16], String[].class);
            String playMode = "spf";
            if (pager == 1) {
                playMode = "rspf";
            }
            initSPF(list, playMode, item.getCodes()[19]);
        }

        void initSPF(List<String[]> strList, String playMode, String danGuanInput) {
            //当前采种下面有几种比例选项 llspf
            String[] strings = strList.get(mType);
            for (int i = 0; i < strings.length; i++) {
                CheckBox cb = (CheckBox) llspf.getChildAt(i);
                if (i == 0) {
                    addBlue(cb, playMode, danGuanInput);
                }
                cb.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        chekedButtonDoOnClick(v);
                    }
                });
                StringBuilder tag = new StringBuilder();
                tag.append(mType == 0 ? "0_spf" : "1_rqspf");
                tag.append("_" + i + "_" + strings[i]);
                if (i == 1) {
                    cb.setText("平" + strings[i]);
                    tag.append("_平");
                } else if (i == 0) {
                    cb.setText("胜" + strings[i]);
                    tag.append("_胜");
                } else if (i == 2) {
                    cb.setText("负" + strings[i]);
                    tag.append("_负");
                }
                tag.append("_" + spf[i]);
                cb.setTag(tag.toString());
                cb.setChecked(isCheckThisView(cb.getTag().toString(), String.valueOf(pager)));
            }
        }
    }

    /**
     * 混合投注的业务逻辑类；
     */
    public class HunTouPresenter {

        public void init(ZqItem item) {
            //这里我们是需要处理对应的业务逻辑的
            mLlHunheBet.setVisibility(View.VISIBLE);
            //这里我们还需要初始化 胜平负、让胜平负左边的小数字；
            mTvSpfTxt.setText("0");
            mTvRqspfTxt.setText(item.getCodes()[5]);
            //已经选中多少项
            String moreCheckBoxText = getMoreCheckBoxText(item);
            if (TextUtils.isEmpty(moreCheckBoxText)) {
                mCbMore.setChecked(false);
                mCbMore.setText("更多玩法");
            } else {
                mCbMore.setText(moreCheckBoxText);
                mCbMore.setChecked(true);
            }
            mCbMore.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    //这里做的一个操作就是
                    execCheckParam((CheckBox) v, "点击选择比分");
                }
            });
            //初始化赔率；
            List<String[]> list = FastOk.getList(item.getCodes()[16], String[].class);
            initSPF(list.get(0), "0_spf", mLlSpf, "0");    //初始化胜平负
            initSPF(list.get(1), "1_rqspf", mLlRqspf, "1");   //初始化让胜平负
        }

        void initSPF(String[] strings, String prefix, ViewGroup group, String selectMapIndex) {
            //当前采种下面有几种比例选项 llspf
            for (int i = 0; i < strings.length; i++) {
                View child = group.getChildAt(i);
                if (child instanceof CheckBox) {
                    CheckBox cb = (CheckBox) group.getChildAt(i);
                    cb.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            chekedButtonDoOnClick(v);
                        }
                    });
                    StringBuilder tag = new StringBuilder();
                    //mType == 0 ? "0_spf":"1_rqspf"
                    tag.append(prefix);
                    tag.append("_" + i + "_" + strings[i]);
                    if (i == 1) {
                        cb.setText("平" + strings[i]);
                        tag.append("_平");
                    } else if (i == 0) {
                        cb.setText("胜" + strings[i]);
                        tag.append("_胜");
                    } else if (i == 2) {
                        cb.setText("负" + strings[i]);
                        tag.append("_负");
                    }
                    tag.append("_" + spf[i]);
                    cb.setTag(tag.toString());
                    cb.setChecked(isCheckThisView(cb.getTag().toString(), selectMapIndex));
                }
            }
        }

        String getMoreCheckBoxText(ZqItem item) {
            //设置默认选中
            String desc = item.getMap() != null && item.getMapLength() > 0 ? "已选中" + item.getMapLength() + "项" : "";
            return desc;
        }
    }


    /**
     * 这里是总进球的一个业务逻辑类；
     */
    public class ZjqPresenter {

        public void init(ZqItem item) {
            //显示；
            mLlZjq.setVisibility(View.VISIBLE);

            List<String[]> list = FastOk.getList(item.getCodes()[16], String[].class);

            initZjq(mLlZjq, list.get(2), item.getCodes()[19]);
        }


        public void initZjq(LinearLayout llAll, String[] strCodeOdd, String danGuanInput) {

            //当前采种下面有几种比例选项
            int childCount = llAll.getChildCount();//混投布局是上下两个linearlayout 每个 linearlayout下四个子view
            int index = 0;
            for (int i = 0; i < childCount; i++) {
                ViewGroup child = (ViewGroup) llAll.getChildAt(i);
                for (int j = 0; j < child.getChildCount(); j++) {
                    CheckBox cb = (CheckBox) child.getChildAt(j);
                    // 判断是否有单关的操作；
                    if (i == 0 && j == 0) {
                        addBlue(cb, "jqs", danGuanInput);
                    }

                    StringBuilder tag = new StringBuilder("2_jqs_" + index + "_" + strCodeOdd[index] + "_" + index + "_" + index);
                    cb.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            chekedButtonDoOnClick(v);
                        }
                    });
                    StringBuilder sb = new StringBuilder();
                    sb.append(index);
                    if (i == childCount - 1 && j == child.getChildCount() - 1)
                        sb.append("球+");
                    else
                        sb.append("球");
                    sb.append("<br/><small><small>");
                    sb.append(strCodeOdd[index]);
                    sb.append("</small></small>");
                    cb.setText(Html.fromHtml(sb.toString()));
                    cb.setTag(tag.toString());
                    cb.setChecked(isCheckThisView(cb.getTag().toString(), "2"));

                    index++;
                }
            }
        }

    }

    /**
     * 这里是单关的逻辑；
     */
    public class DgPresenter {

        public void init(ZqItem item) {
            //这里我们处理单关的逻辑

            //这里我们是需要处理对应的业务逻辑的
            mLlDanGuanBet.setVisibility(View.VISIBLE);
            //这里我们还需要初始化 胜平负、让胜平负左边的小数字；
            mTvDanGuanSpfTxt.setText("0");
            mTvDanGuanRqspfTxt.setText(item.getCodes()[5]);
            //已经选中多少项
            String moreCheckBoxText = getMoreCheckBoxText(item);
            if (TextUtils.isEmpty(moreCheckBoxText)) {
                mCbDanGuanMore.setChecked(false);
                mCbDanGuanMore.setText("更多玩法");
            } else {
                mCbDanGuanMore.setText(moreCheckBoxText);
                mCbDanGuanMore.setChecked(true);
            }
            mCbDanGuanMore.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    //这里做的一个操作就是
                    execCheckParam((CheckBox) v, "点击选择比分");
                }
            });
            //初始化赔率；
            List<String[]> list = FastOk.getList(item.getCodes()[16], String[].class);
            initSPF(list.get(0), "0_spf", mLlDanGuanSpf, "0");    //初始化胜平负
            initSPF(list.get(1), "1_rqspf", mLlDanGuanRqspf, "1");   //初始化让胜平负

            isDanGuan("spf", item.getCodes()[19]);
            isDanGuan("rspf", item.getCodes()[19]);

        }

        private void isDanGuan(String playMode, String input) {

            if ("spf".equals(playMode)) {
                //判断胜平负，是否支持单关；
                if (isSupportDanGuan(playMode, input)) {
                    mLlDanGuanSpf.setVisibility(View.VISIBLE);
                    mTvDanGuanSpfNoSale.setVisibility(View.INVISIBLE);
                } else {
                    mLlDanGuanSpf.setVisibility(View.INVISIBLE);
                    mTvDanGuanSpfNoSale.setVisibility(View.VISIBLE);
                }
            } else if ("rqspf".equals(playMode)) {
                //让胜平负是否支持单关；
                if (isSupportDanGuan(playMode, input)) {
                    mLlDanGuanRqspf.setVisibility(View.VISIBLE);
                    mTvDanGuanRspfNoSale.setVisibility(View.INVISIBLE);
                } else {
                    mLlDanGuanRqspf.setVisibility(View.INVISIBLE);
                    mTvDanGuanRspfNoSale.setVisibility(View.VISIBLE);
                }
            }
        }

        void initSPF(String[] strings, String prefix, ViewGroup group, String selectMapIndex) {
            //当前采种下面有几种比例选项 llspf
            for (int i = 0; i < strings.length; i++) {
                View child = group.getChildAt(i);
                if (child instanceof CheckBox) {
                    CheckBox cb = (CheckBox) group.getChildAt(i);
                    cb.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            chekedButtonDoOnClick(v);
                        }
                    });
                    StringBuilder tag = new StringBuilder();
                    //mType == 0 ? "0_spf":"1_rqspf"
                    tag.append(prefix);
                    tag.append("_" + i + "_" + strings[i]);
                    if (i == 1) {
                        cb.setText("平" + strings[i]);
                        tag.append("_平");
                    } else if (i == 0) {
                        cb.setText("胜" + strings[i]);
                        tag.append("_胜");
                    } else if (i == 2) {
                        cb.setText("负" + strings[i]);
                        tag.append("_负");
                    }
                    tag.append("_" + spf[i]);
                    cb.setTag(tag.toString());
                    cb.setChecked(isCheckThisView(cb.getTag().toString(), selectMapIndex));
                    //在这里我们进行一个判断，是否支持单关，如果不支持;
                }
            }
        }

        String getMoreCheckBoxText(ZqItem item) {
            //设置默认选中
            String desc = item.getMap() != null && item.getMapLength() > 0 ? "已选中" + item.getMapLength() + "项" : "";
            return desc;
        }

    }


    /**
     * 判断是否支持单关；
     *
     * @param view     如果支持单关，在view上添加一个小蓝点；
     * @param playMode 用户的玩的模式；
     * @param input    这场比赛的支持单关的输入情况；
     * @return true 表示支持单关，添加一个view，false表示不支持,没有添加
     */
    void addBlue(TextView view, String playMode, String input) {

        if (isSupportDanGuan(playMode, input)) {
            addBlue(view);
        }
    }

    /**
     * 添加一个小蓝点，没有要求；
     *
     * @param view 需要添加小蓝点的位置；
     */
    @TargetApi(Build.VERSION_CODES.M)
    public void addBlue(TextView view) {
        int cH = ScreenUtil.dip2px(view.getContext(), 20);
        view.setCompoundDrawables(null, null, null, null);
        Drawable myImage = ContextCompat.getDrawable(getContext(), R.mipmap.img_danguan);
        myImage.setBounds(0, -10, cH, cH);
        view.setCompoundDrawables(myImage, null, null, null);
    }

    /**
     * 判断是否支持单关；
     *
     * @param playMode
     * @param input
     * @return true表示支持，false表示不支持；
     */
    public boolean isSupportDanGuan(String playMode, String input) {
        int mid = -1;
        switch (playMode) {
            case "bqc":
                mid = 0;
                break;
            case "cbf":
                mid = 1;
                break;
            case "jqs":
                mid = 2;
                break;
            case "rqspf":
                mid = 3;
                break;
            case "spf":
                mid = 4;
                break;
        }
        int value = TextUtils.isEmpty(input) ? 0 : Integer.parseInt(input);
        //判断是否支持单关；
        return ((value & 1 << mid) == (1 << mid));
    }
}
